package com.xxl.job.executor.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections.MapUtils;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Map;

/**
 * ok http请求工具类
 */
@Slf4j
public class OkHttpUtils {

    public static final String APP_JSON = "application/json";

    public static final String RESP_CODE_200 = "200";

    /**
     * get方式请求
     */
    public static Response getRequest(String url) throws IOException{
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        return okHttpClient.newCall(request).execute();
    }


    /**
     * post方式请求提交json字符串，可设置header
     */
    public static Response postJsonRequest(String url, String jsonBody, Map<String, String> headerMap) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse(APP_JSON);
        RequestBody requestBody = RequestBody.create(mediaType, jsonBody);
        Request.Builder builder = new Request.Builder();
        if(MapUtils.isNotEmpty(headerMap)){
            headerMap.entrySet().forEach(entry -> {
                builder.addHeader(entry.getKey(), entry.getValue());
            });
        }
        Request request = builder.url(url).post(requestBody).build();
        return okHttpClient.newCall(request).execute();
    }

    /**
     * 同步post方式请求-form表单提交参数
     *
     * @param url
     * @param paramsMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramsMap) throws IOException {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : paramsMap.keySet()) {
            builder.add(key, paramsMap.get(key));
        }
        RequestBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    /**
     * 异步get方式请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static void doSyncGet(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new OkHttpCallback());
    }

    /**
     * 异步post方式请求-json提交参数
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static void doSyncPost(String url, final String json) {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse(APP_JSON);
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new OkHttpCallback());

    }

    /**
     * 异步post方式请求-form表单提交参数
     *
     * @param url
     * @param paramsMap
     * @return
     * @throws IOException
     */
    public static void doSyncPost(String url, Map<String, String> paramsMap) {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : paramsMap.keySet()) {
            builder.add(key, paramsMap.get(key));
        }
        RequestBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new OkHttpCallback());

    }

    /**
     * okhttp 异步调用回调函数
     */
    static class OkHttpCallback implements Callback {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            log.error(e.getMessage());
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if (response.isSuccessful()) {
                log.info("Successful data acquisition . . . ");
                log.info("response.code()==" + response.code());
                log.info("response.body().string()==" + response.body().string());
            }
        }
    }
}
